var common = require("../../utils/Conmon.js");
// pages/topup/topup.js
var appData = getApp().globalData
Page({

  /**
   * 页面的初始数据
   */
  data: {
    payMethods: [],
    Money: '',
    CssType: 'btn-custom',
    payName: '',
    payTypeId: '',
    rechargeType: 1 //默认佣金
  },

  /**
   * 输入充值金额
   */
  bindMoneyInput: function(e) {
    var that = this;
    var money = e.detail.value;
    var css = 'btn-custom';
    if (Number(money) < 0 || money == '') {
      css = 'btn-custom';
      money = '';
    }
    if (Number(money) > 0) {
      css = 'btn-primary';
    }
    that.setData({
      CssType: css,
      Money: money
    })
  },
  /**
   * 确定去充值（生成充值订单）
   */
  BindToPupClickTap: function(e) {
    var that = this;
    if (that.data.CssType == 'btn-custom') {
      return;
    }
    var money = Number(that.data.Money);
    if (money <= 0)
      return;
    wx.showLoading({
      title: '充值中...',
      mask: true
    });
    //提交生成充值订单
    wx.request({
      url: appData.apiurl + 'member/api/Recharge/AddOrder',
      method: 'POST',
      data: {
        "UserID": wx.getStorageSync('UserInfo').UserID,
        "CustID": appData.custID,
        "OrderMoney": money,
        "RechargeType": that.data.rechargeType
      },
      header: {
        "content-type": "application/json",
        'X_ManuName': appData.manuName
      },
      success: function(res) {
        wx.hideLoading()
        if (res.statusCode == 200 && res.data.code == 1200) {
          var orderId = res.data.content == null ? '0' : res.data.content.RechargeOrder;
          //调用微信SDK充值 (去充值)
          that.bindGoRecharge(orderId);
        } else if (res.data.code == 1500) {
          wx.showModal({
            title: '错误',
            content: '暂不支持该种充值类型',
            showCancel: false
          })
        } else {
          wx.showModal({
            title: '错误',
            content: '充值失败',
            showCancel: false
          })
        }
      },
      fail: function(res) {
        wx.hideLoading()
        wx.showModal({
          title: '错误',
          content: '充值失败',
          showCancel: false
        })
      }
    })
  },

  /**
   * 调SDK充值
   */
  bindGoRecharge: function(orderId) {
    var that = this;
    var openid = wx.getStorageSync('openId');
    wx.request({
      url: appData.apiurl + '/mobile/api/Recharge/GoRecharge2',
      data: {
        "custId": appData.custID,
        "userId": wx.getStorageSync('UserInfo').UserID,
        "orderId": orderId,
        "openId": openid,
        "payTypeId": that.data.payTypeId
      },
      method: 'GET',
      header: {
        "content-type": "application/json",
        'X_ManuName': appData.manuName
      },
      success: function(res) {
        if (res.statusCode == 200 && res.data.code == 1200) {
          var jsonStr = JSON.parse(res.data.content);
          wx.requestPayment({
            'timeStamp': jsonStr.timeStamp,
            'nonceStr': jsonStr.nonceStr,
            'package': jsonStr.package,
            'signType': jsonStr.signType,
            'paySign': jsonStr.paySign,
            'success': function(res) {
              that.SuccesscallBack(that, orderId);
            },
            'fail': function(res) {
              that.FailcallBack(that, orderId);
            }
          });
        } else {
          wx.showModal({
            title: '错误',
            content: '充值失败',
            showCancel: false
          })
        }
      },
      fail: function(res) {
        wx.showModal({
          title: '错误',
          content: '充值失败',
          showCancel: false
        })
      }
    })
  },

  /**
   * 获取选中的支付方式
   */
  bindRadioClick: function(e) {
    var that = this;
    var _payName = e.currentTarget.dataset.payname;
    var _payTypeId = e.currentTarget.dataset.paytypeid;
    var payMethods = that.data.payMethods;
    for (var i = 0; i < payMethods.length; i++) {
      if (payMethods[i].PayTypeID == _payTypeId) {
        payMethods[i].IsCheck = true;
      } else {
        payMethods[i].IsCheck = false;
      }
    }
    that.setData({
      payMethods: payMethods,
      payTypeId: _payTypeId,
      payName: _payName
    })
  },

  /**
   * 获取充值方式
   */
  bindRechargeMethod: function() {
    var that = this;
    wx.request({
      url: appData.apiurl + 'member/api/OrderForm/GetPayTypeListByTerminal',
      method: 'GET',
      data: {
        "custId": appData.custID,
        "useTerminal": 3
      },
      header: {
        "content-type": "application/json",
        'X_ManuName': appData.manuName
      },
      success: function(res) {
        wx.hideLoading()
        if (res.statusCode == 200 && res.data.code == 1200) {
          if (res.data.content != null) {
            var payMethods = res.data.content;
            var payWays=new Array();
            for (var i = 0; i < payMethods.length; i++) {
              if (payMethods[i].PayName.indexOf('微信支付')>-1)
              {
                if (i == 0) {
                  payMethods[i].IsCheck = true;
                } else {
                  payMethods[i].IsCheck = false;
                }
                payWays.push(payMethods[i]);
              }
            
            }
            that.setData({
              payMethods: payWays,
              payTypeId: res.data.content[0].PayTypeID,
              payName: res.data.content[0].PayName
            });
          }
        } else {
          wx.showModal({
            title: '错误',
            content: '获取失败',
            showCancel: false
          })
          console.log(res.data)
        }
      },
      fail: function(res) {
        wx.hideLoading()
        wx.showModal({
          title: '错误',
          content: '请求获取异常错误',
          showCancel: false
        })
        console.log(res.data)
      }
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    common.pageInit(function() {});

    var rechargeType = options.type;
    var that = this;
    if (rechargeType != null && rechargeType != undefined) {
      that.setData({
        rechargeType: rechargeType
      });
    }

    wx.showLoading({
      title: '加载中...',
      mask: true
    });
    this.bindRechargeMethod();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})

/**
 * 成功支付回调
 */
function SuccesscallBack(that, orderId) {
  wx.request({
    url: appData.apiurl + '/mobile/api/Recharge/PayCompleteCallBack',
    data: {
      custId: appData.custID,
      orderId: orderId
    },
    header: {
      'X_ManuName': appData.manuName
    },
    method: 'GET',
    success: function(res) {
      if (res.statusCode == 200 && res.data.code == 1200) {
        var recharge = res.data.content;
        var money = 0; //充值金额
        if (recharge != null)
          money = recharge.OrderMoney;

        wx.redirectTo({
          url: '/pages/topupSucceed/topupSucceed?orderMoney=' + money
        });

      } else {
        wx.showModal({
          content: res.data.msg,
          showCancel: false,
          confirmText: "确定"
        })
      }
    }
  })
}

/**
 * 失败支付回调
 */
function FailcallBack(that, orderId) {
  wx.redirectTo({
    url: '/pages/topupFail/topupFail?orderId=' + orderId
  });
}